//  小ref 与大Ref的区别？
import { ref, Ref } from 'vue'
//  定义接口
interface PicType {
  appRef: Ref<HTMLElement>
  calcRate: () => void
  windowDraw: () => void
}
export default function useIndex(): PicType {
  // * 绑定外层节点上面的ref
  const appRef = ref()
  // * 定时函数
  const timer = ref(0)
  // * 默认缩放值
  const scale = {
    width: '1920',
    height: '1080'
  }
  // * 设计稿尺寸（px）
  const baseWidth = 1920
  const baseHeight = 1080
  // * 需保持的比例（默认1.77778）
  const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))

  const calcRate = () => {
    // 当前宽高比 
    /* 
      window.innerWidth 和 document.body.clientWidth 区别
      window.innerWidth 会更大 会把 滚动条 宽度算进去
    */   
    const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5))
    if (appRef.value) {
      if (currentRate > baseProportion) {
        // 表示更宽, 就要减少宽度, 比例按照高度走
        // scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5)
        scale.height = (window.innerHeight / baseHeight).toFixed(5)
        // appRef.value.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
        appRef.value.style.transform = `scale(${scale.height}) translate(-50%, -50%)`
      } else {
        // 表示更高，就要减少高度, 比例按照宽度走
        // scale.height = (window.innerWidth / baseProportion / baseHeight).toFixed(5)
        scale.width = (window.innerWidth / baseWidth).toFixed(5)
        // appRef.value.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
        appRef.value.style.transform = `scale(${scale.width}) translate(-50%, -50%)`
      }
    }
  }

  const resize = () => {
    clearTimeout(timer.value)
    // 要使用window.setTimeout 不然会有出错
    timer.value = window.setTimeout(() => {
      calcRate()
    }, 200)
  }

  // 改变窗口大小重新绘制
  const windowDraw = () => {
    window.addEventListener('resize', resize)
  }

  return {
    appRef,
    calcRate,
    windowDraw
  }
}
